package com.xjk.sifasuo.fragment;

import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.Toast;

import com.xjk.sifasuo.utils.PermissionUtils;

/**
 * Created by zhouzhuo on 2017/6/29.
 */

public class BaseFragment extends Fragment implements View.OnClickListener{

    @Override
    public void onClick(View v) {

    }

    //下面是权限相关代码----------------------------------------!
    /**
     * 权限回调Handler
     */
    private PermissionHandler mHandler;

    /**
     * 请求权限
     *
     * @param permissions 权限列表
     * @param handler     回调
     */
    public void requestPermission(String[] permissions, PermissionHandler handler) {
        String permissionArr[] = PermissionUtils.hasSelfPermissions(getActivity(), permissions);
        if (permissionArr.length==0) {
            handler.onGranted();
        } else {
            mHandler = handler;
            ActivityCompat.requestPermissions(getActivity(), permissionArr, 001);
        }
    }


    /**
     * 权限请求结果
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (mHandler == null) return;

//        if (PermissionUtils.getTargetSdkVersion(this) < 23 && !PermissionUtils.hasSelfPermissions(this, permissions)) {
//            mHandler.onDenied();
//            return;
//        }

        if (PermissionUtils.verifyPermissions(grantResults)) {
            mHandler.onGranted();
        } else {
            if (!PermissionUtils.shouldShowRequestPermissionRationale(getActivity(), permissions)) {
                if (!mHandler.onNeverAsk()) {
                    Toast.makeText(getActivity(), "权限已被拒绝,请在设置-应用-权限中打开", Toast.LENGTH_SHORT).show();
                }

            } else {
                mHandler.onDenied();
            }
        }
    }


    /**
     * 权限回调接口
     */
    public interface PermissionHandler {
        /**
         * 权限通过
         */
        void onGranted();

        /**
         * 权限拒绝
         */
        void onDenied();

        /**
         * 不再询问
         *
         * @return 如果要覆盖原有提示则返回true
         */
        boolean onNeverAsk();
    }
}
